package com.duguo.dynamicmvc.model;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.duguo.dynamicmvc.factory.utils.BeanUtils;

public class ModelImpl implements Model {
	
    private Map map;

    public int size() {
        return keySet().size();
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public boolean containsKey(Object key) {
        return get(key) != null;
    }

    public boolean containsValue(Object value) {
        for (Object currentValue : values())
            if (currentValue == value)
                return true;
        return false;
    }

    public Object get(Object key) {
    	if(map!=null)
            return map.get(key);
        return null;
    }

    @SuppressWarnings("unchecked")
    public Object put(Object key, Object value) {
    	if(map!=null)
            return map.put(key, value);
    	else{
            map = new HashMap(1);
            map.put(key, value);
        }
        return null;
    }

    public Object remove(Object key) {
    	if(map!=null)
            return map.remove(key);
        return null;
    }

    public void putAll(Map t) {
    	for(Object key:t.keySet()){
    		put(key,t.get(key));
    	}
    }

    public void clear() {
    	if(map!=null)
            map.clear();
    }

    public Set keySet() {
    	if(map!=null)
            return map.keySet();
        return Collections.EMPTY_SET;
    }

    public Collection values() {
    	if(map!=null)
            return map.values();
        return Collections.EMPTY_LIST;
    }

    public Set entrySet() {
    	if(map!=null)
            return map.entrySet();
        return Collections.EMPTY_SET;
    }
    
    public String toString(){
    	if(map!=null){
	    	StringBuffer sb=new StringBuffer();
	    	for(Object obj:entrySet()){
	    		Map.Entry entry=(Map.Entry)obj;
	    		if(sb.length()>0)
	        		sb.append(", ");
	    		sb.append(entry.getKey());
	    		sb.append("[");
	    		BeanUtils.inspectObject(sb,entry.getValue());
	    		sb.append("]");
	    	}
	    	return sb.toString();
    	}else{
    		return null;
    	}
    }

}
